use askama::Template;
use axum::{extract::Query, response::IntoResponse};
use tower_cookies::Cookies;

use crate::{
    domain::topic::Topic, service::search_service, QueryParam, TemplateResponse,
    TOKEN_NAME,
};

use super::base::{base, BaseData, Pagination};
use crate::template::filters;

#[derive(Template)]
#[template(path = "search.html")]
pub struct SearchTemplate {
    page: Pagination<Topic>,
    base: BaseData,
}

pub async fn index(cookies: Cookies, param: Query<QueryParam>) -> impl IntoResponse {
    let param = &param.0;
    let login = cookies.get(TOKEN_NAME).map_or(false, |_| true);
    let page = search_service::search(param, login);
    let page = Pagination::new(page);
    let mut template = SearchTemplate {
        page: page,
        base: base(cookies).await,
    };
    template.base.kw = Some(param.kw.to_owned().unwrap());
    TemplateResponse(template)
}
